package org.szy.core.event.monitor.handle;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import org.noear.solon.core.event.EventBus;
import org.szy.core.event.monitor.contant.OnlineConstants;

import java.util.Date;


/**
 * 在线用户拦截器
 *
 * @author 孙志阳
 * @date 2023-07-05
 * @since 1.0.0
 **/
public class UserOnlineRouterHandle {


    public static void doIntercept(SaTokenInfo token, SaSession session) {
        try {

            // 更新用户最后活动时间
            Date lastSyncTimestamp = (Date) session.get(OnlineConstants.LAST_SYNC_DB_TIMESTAMP);
            Date now = new Date();

            long activityTimeout = token.getTokenActivityTimeout();
            int maxValue = Integer.MAX_VALUE;
            int second = activityTimeout == -1 ? maxValue : activityTimeout > maxValue ? maxValue : Convert.toInt(activityTimeout);

            session.set(OnlineConstants.EXPIRATION_DATETIME, DateUtil.offsetSecond(now, second));

            if (ObjUtil.isNull(lastSyncTimestamp) || (now.getTime() - lastSyncTimestamp.getTime()) > OnlineConstants.SYNC_PERIOD) {
                session.set(OnlineConstants.LAST_SYNC_DB_TIMESTAMP, now);
                EventBus.pushAsync(token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
